package foliotracker.controllers;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import foliotracker.IStockPriceService;
import foliotracker.Portfolio;
import foliotracker.Stock;
import foliotracker.StockPriceServiceException;
import foliotracker.UnknownStockSymbolException;
import foliotracker.YahooStockPriceService;
import foliotracker.views.IBuyStockView;

public class BuyStockController
{
	private IBuyStockView view;
	private Portfolio portfolio;
	
	//these fields are set when validate is called
	private int quantity;
	private String symbol, name;
	private double cost, price;
	private Date date;
	
	public BuyStockController(Portfolio portfolio)
	{
		this.portfolio = portfolio;
	}
	
	public List<String> getSymbols()
	{
		List<String> symbols = new ArrayList<String>();
		
		for (Stock stock: portfolio.getStocks())
		{
			symbols.add(stock.getSymbol());
		}
		
		return symbols;
	}
	
	public void setView(IBuyStockView view)
	{
		this.view = view;	
	}
	
	/**
	 * Gets the appropriate values from the view and then calls the buy method on the portfolio.
	 */
	public void buyStock()
	{
		//these values will be filled in by calling validate()
		portfolio.buyStock(symbol, name, date, quantity, cost, price);
	}
	
	/**
	 * Checks that all the required values are present and correct; if they aren't, the relevant view.set...Error is called.
	 * @return True if the validation succeeded; otherwise, false.
	 */
	
	public boolean validate()
	{
		boolean success = true;
		
		symbol = view.getSymbol();
		
		try
		{
			IStockPriceService service = new YahooStockPriceService();
			name = service.getStockName(view.getSymbol());
			price = service.getStockPrice(view.getSymbol());
		}
		catch (UnknownStockSymbolException ex)
		{
			view.setSymbolError("Invalid symbol");
			success = false;
		}
		catch (StockPriceServiceException ex)
		{
			view.setSymbolError("Error reaching stock service");
			success = false;
		}
		
		try
		{
			quantity = Integer.parseInt(view.getQuantityField());
		}
		catch (NumberFormatException ex)
		{
			view.setQuantityError("Invalid integer");
			success = false;
		}
		
		try
		{
			cost = Double.parseDouble(view.getCostField());
		}
		catch (NumberFormatException ex)
		{
			view.setCostError("Invalid cost");
			success = false;
		}
		
		try
		{
			DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
			date = format.parse(view.getDateField());
		}
		catch (ParseException ex)
		{
			view.setDateError("Invalid date (dd/mm/yyyy)");
			success = false;
		}
		
		return success;
	}
}
